import cv2
from fastapi import APIRouter,Request
from openai import OpenAI
import json
import os
from app.config.setting import Settings as settings
from langchain_community.llms import Ollama
import requests
from fastapi.responses import JSONResponse
from typing import Optional, Dict, Any
from pydantic import BaseModel


router = APIRouter()

@router.get("/test")
async def test():
    return {"message": "Hello, World!"}


class chatimagesV1Schema(BaseModel):
    inputText: Optional[str] = None

## 可以考虑直接只用post的方式实现
@router.post("/ollama_chattext")
async def OllamaChatimagesV1(request: chatimagesV1Schema):
    try:
        inputText = request.inputText or ""
        OLLAMABASEURL = "http://172.16.21.38:11436"
        OLLAMABASEURL = OLLAMABASEURL+"/api/chat"
        OLLAMAMODEL = "qwen3:0.6b"

        headers = {"Content-Type": "application/json"}
        data = {
            "model": OLLAMAMODEL,  # 模型选择
            "options": {
                "temperature": 0.  # 为0表示不让模型自由发挥，输出结果相对较固定，>0的话，输出的结果会比较放飞自我
            },
            "stream": False,  # 流式输出
            "messages": [{
                "role": "system",
                "content": inputText  # 系统提示词
            }]  # 对话列表
        }
        response = requests.post(OLLAMABASEURL, json=data, headers=headers, timeout=60)
        if response.status_code == 200:
            try:
                res_json = response.json()
                responseModel = res_json.get('model', '')
                responseCreatedAt = res_json.get('created_at', '')
                responseMessage = res_json.get('message', {})
                responseMessageContent = responseMessage.get('content', '')
                return JSONResponse(content={
                    "code": 200,
                    "message": "识别成功",
                    "responseMessageContent": responseMessageContent
                })
            except Exception as e:
                return JSONResponse(content={
                    "code": 500,
                    "message": f"解析返回结果失败: {str(e)}"
                })
        else:
            return JSONResponse(content={
                "code": 400,
                "message": f"失败: {str(response.status_code)}"})
    except Exception as e:
        return JSONResponse(content={
            "code": 400,
            "message": f"失败: {str(e)}"})